package com.cx.mall.user.service.impl;

import com.cx.mall.user.dao.impl.UserInfoDaoImpl;
import com.cx.mall.user.dao.impl.UserLoginLogDaoImpl;
import com.cx.mall.user.entity.UserInfo;
import com.cx.mall.user.entity.UserLoginLog;
import com.cx.mall.user.service.IUserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.time.LocalDateTime;
@Service
public class UserLoginBaseServiceImpl implements IUserLoginService {
    @Autowired
    private UserInfoDaoImpl userInfoDao ;
    @Autowired
    private UserLoginLogDaoImpl userLoginLogDao;

    @Override
    public UserInfo login(String username, String password) throws Exception {
        // 按用户名查询
        UserInfo userInfo = userInfoDao.selectOne(username);
        // 比较密码
        if(userInfo != null){
            if(password.equals(userInfo.getPassword())){
                // 写登录日志
                // 获取主机 Ip
                InetAddress inetAddress = InetAddress.getLocalHost();
                String ip = inetAddress.getHostAddress();
                UserLoginLog log = new UserLoginLog(
                        System.currentTimeMillis(),
                        userInfo.getId(),
                        LocalDateTime.now(),
                        ip);
                userLoginLogDao.insert(log);
                return userInfo;
            }else {
                throw new Exception("密码错误");
            }
        }else {
            throw new Exception("用户名错误或用户已禁用");
        }
    }
}